package com.ntlabs.android;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

public class FrameThread extends Thread {

	private final Lock lock = new ReentrantLock();
	private final Condition onNewFrame = lock.newCondition();
	private final Condition onPause = lock.newCondition();
	private final Condition onRelease = lock.newCondition();
	private boolean isPaused = false;
	private static int deltaT = 20;
	private boolean newFrame = false;
	private long frames = 0;
	private boolean running = true;
	private boolean released = false;
	
	public FrameThread() {
		
	}
	
	public boolean release() {
		this.running = false;
		this.lock.lock();
		while(!this.released) {
			try {
				this.onRelease.await();
			} catch (Exception e) {
				
			}
		}
		this.lock.unlock();
		return true;
	}
	
	public long getFrame() {
		try {
			this.lock.lock();
			while(!this.newFrame) {
				this.onNewFrame.await();
			}
			this.lock.unlock();
		} catch (Exception e) {
			
		}
		this.newFrame = false;
		return this.frames;
	}
	
	public void onPause() {
		this.lock.lock();
		this.isPaused = true;
		this.lock.unlock();
	}
	
	public void onResume() {
		this.lock.lock();
		this.isPaused = false;
		this.onPause.signal();
		this.lock.unlock();
	}
	
	@Override
	public void run() {
		while(this.running) {
			try {
				Thread.sleep(this.deltaT);
			} catch (Exception e) {
				
			}
			this.lock.lock();
			while(this.isPaused) {
				try {
					this.onPause.await();
				} catch (InterruptedException e) {
					
				}
			}
			this.newFrame = true;
			this.onNewFrame.signal();
			this.frames++;
			this.lock.unlock();
		}
		this.lock.lock();
		this.released = true;
		this.onRelease.signal();
		this.lock.unlock();
	}
	
	//Test
	
	/*public static void main(String[] args) {
		FrameThread ft = new FrameThread();
		int i = 0;
		ft.start();
		while (i < 100) {
			i = ft.getFrame();
			System.out.println(i);
		}
		ft.release();
	}*/
	
}
